<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    style="min-width: 1500px;"
    :visible.sync="visible" width="60%">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="80px" size="small">
      <div class="item-wrapper">
        <el-form-item label="绘本名称" prop="name">
          <el-input v-model="dataForm.name" placeholder="请输入绘本名称" style="width: 200px;"></el-input>
        </el-form-item>
        <el-form-item label="副标题" prop="descr">
          <el-input v-model="dataForm.descr" placeholder="请输入副标题名称" style="width: 200px;" maxlength=20></el-input>
        </el-form-item>
        <el-form-item label="来源" prop="source">
        <el-select v-model="dataForm.source">
          <el-option
            v-for="item in sourceOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
        <el-form-item label="绘本类型" prop="showType">
          <el-select v-model="dataForm.showType">
            <el-option
              v-for="item in showTypeOptions"
              :key="item.id"
              :label="item.label"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="绘本分类" prop="contentType">
          <el-select v-model="dataForm.contentType" multiple>
            <el-option
              v-if="contentTypeOptions"
              v-for="item in contentTypeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="适合年龄" prop="ageRange">
          <el-select v-model="dataForm.ageRange">
            <el-option
              v-for="item in ageRangeOptions"
              :key="item.id"
              :label="item.label"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="购买权限" prop="payRight" class="no-bottom-margin">
          <el-select v-model="dataForm.payRight">
            <el-option
              v-for="item in payRightOptions"
              :key="item.id"
              :label="item.label"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </div>
      <div class="item-wrapper">
        <div class="price-item-wrapper">
          <span>绘本价格：</span>
          <div style="margin: 0 30px;">
            单册价格
            <input :value="dataForm.price" placeholder="短期不收费" class="price-input" @input="oninput" type="number"
                   ref="price" :disabled="dataForm.source == 'QT2'"/>
          </div>
          整套价格
          <input :value="dataForm.pricePkg" placeholder="短期不收费" @input="oninput" class="price-input" type="number"
                 ref="pricePkg" :disabled="dataForm.source == 'QT2'"/>
                 <div style="margin: 0 30px;">
          试听册数
          <el-input v-model="dataForm.freeAmount" placeholder="请输入整数" style="width:120px;" onpaste="return false;" oninput="if(value>10000)value=10000;if(value.length>5)value=value.slice(0,5);if(value<1)value=1" type="number" ref="freeAmount"></el-input>
        </div>
        </div>
        <div class="price-item-wrapper" style="margin-top: 12px">
          <span style="color: red;">会员价格：</span>
          <div style="margin: 0 30px;">
            单册价格
            <input :value="dataForm.priceVip" placeholder="短期不收费" @input="oninput" class="price-input" type="number"
                   ref="priceVip" :disabled="dataForm.source == 'QT2'"/>
          </div>
          整套价格
          <input :value="dataForm.pricePkgVip" placeholder="短期不收费" @input="oninput" class="price-input" type="number"
                 ref="pricePkgVip" :disabled="dataForm.source == 'QT2'"/>
        </div>
      </div>
      <div class="item-wrapper" style="display: flex;flex-direction: row;">
        <div class="item-pic-wrapper" style="margin-right: 150px;">
          <span style="color: #f56c6c;margin-right: 4px">*</span>封面绘本：
          <div style="font-size: 12px;margin-right: 6px;">限传一张图片,图片尺寸最佳为400X480像素</div>
          <div class="coverImg-wrapper pic">
            <el-upload
              ref="uploadCoverImg"
              :action="uploadImgUrl"
              :on-success="handleCoverImgSuccess"
              :on-error="handleCoverImgError"
              :show-file-list="showCoverImgUpload"
              :before-upload="beforeCoverImgUpload">
              <img v-if="dataForm.coverImg" :src="dataForm.coverImg" class="coverImg">
              <i v-else class="el-icon-plus coverImg-uploader-icon"></i>
            </el-upload>
            <!--<span style="font-size: 12px;margin-left: 12px;margin-right: 6px;">限传一张图片,图片尺寸最佳为400X480像素</span>-->
          </div>
          <span class="error-tip">{{coverImgErrorTip}}</span>
        </div>
        <div class="item-pic-wrapper">
          <span> 轮播图：</span>
          <div style="font-size: 12px;margin-right: 6px;">限传一张轮播图,图片尺寸最佳为960X540像素</div>
          <div class="bannerImg-wrapper pic">
            <el-upload
              ref="uploadBannerImg"
              :action="uploadImgUrl"
              :show-file-list="showBannerImgUpload"
              :on-success="handleBannerImgSuccess"
              :on-error="handleBannerImgError"
              :before-upload="beforeBannerImgUpload">
              <img v-if="dataForm.bannerImg" :src="dataForm.bannerImg" class="bannerImg">
              <i v-else class="el-icon-plus bannerImg-uploader-icon"></i>
            </el-upload>

          </div>
          <span class="error-tip">{{bannerImgErrorTip}}</span>
        </div>
        <div class="item-pic-wrapper">
          <span> 背景图：</span>
          <div style="font-size: 12px;margin-right: 6px;">限传一张背景图,图片尺寸最佳为960X540像素</div>
          <div class="bannerImg-wrapper pic">
            <el-upload
              ref="uploadScreenImg"
              :action="uploadImgUrl"
              :show-file-list="showScreenImgUpload"
              :on-success="handleScreenImgSuccess"
              :on-error="handleScreenImgError"
              :before-upload="beforeScreenImgUpload">
              <img v-if="dataForm.screenImg" :src="dataForm.screenImg" class="bannerImg">
              <i v-else class="el-icon-plus bannerImg-uploader-icon"></i>
            </el-upload>

          </div>
          <span class="error-tip">{{screenImgErrorTip}}</span>
        </div>
      </div>
      <div class="item-wrapper">
        绘本简介:
        <div>
          <el-input v-model="dataForm.summary" type="textarea" :rows="5" maxlength="240" placeholder="240字内"></el-input>
        </div>
      </div>
      <div class="item-wrapper">
        <div style="margin-bottom: 12px;">上下架：</div>
        <el-radio v-model="dataForm.status" :label="1">上架</el-radio>
        <el-radio v-model="dataForm.status" :label="0">下架</el-radio>
      </div>
    </el-form>
    <span slot="footer" class="dialog-footer">
       <el-button type="success" @click="previewPicBook()">预览</el-button>
      <el-button type="primary" @click="dataFormSubmit()">提交</el-button>
      <el-button @click="visible = false">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        visible: false,
        coverImgErrorTip: '',
        showCoverImgUpload: true,
        bannerImgErrorTip: '',
        showBannerImgUpload: true,
        screenImgErrorTip: '',
        showScreenImgUpload: true,
        uploadCoverImgUrl: this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`),
        uploadBannerImgUrl: this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`),
        uploadImgUrl: this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`),
        showTypeOptions: [
          {id: 0, label: '普通绘本'},
          {id: 1, label: '互动绘本'},
          {id: 2, label: '精读绘本'},
          {id: 3, label: '配音绘本'},
          {id: 4, label: '音频故事(听书)'}
        ],
        contentTypeOptions: [],
        sourceOptions: [],
        // contentTypeOptions: [
        //   {id: 1, label: '情商培养'},
        //   {id: 2, label: '国学'},
        //   {id: 3, label: '逻辑思维'},
        //   {id: 99, label: '其他'},
        // ],
        ageRangeOptions: [
          {id: 0, label: '0~3岁'},
          {id: 4, label: '4~6岁'},
          {id: 7, label: '7岁以上'},
        ],
        payRightOptions: [{id: 'all', label: '全部'}, {id: 'serial', label: '全册'}],
        showCoverImgErrorTip: false,
        dataForm: {
          code: '',
          name: '',
          descr: '',
          showType: 0,
          contentType: [],
          contentTypeName: '',
          ageRange: 0,
          payRight: 'all',
          price: '',
          pricePkg: '',
          priceVip: '',
          pricePkgVip: '',
          coverImg: '',
          bannerImg: '',
          screenImg: '',
          itemCount: '',
          status: 1,
          source: '',
          summary: '',
          freeAmount: '',
          remark: ''
        }
        ,
        dataRule: {
          name: [
            {required: true, message: '绘本名称不能为空', trigger: 'blur'}
          ],
          showType:
            [
              {required: true, message: '绘本类型不能为空', trigger: 'blur'}
            ],
          contentType:
            [
              {required: true, message: '绘本分类不能为空', trigger: 'blur'}
            ],
          ageRange:
            [
              {required: true, message: '年龄范围(如:0~3岁)不能为空', trigger: 'blur'}
            ],
          payRight:
            [
              {required: true, message: '购买权限不能为空', trigger: 'blur'}
            ],
          price:
            [
              {required: true, message: '单册价格不能为空', trigger: 'blur'}
            ],
          pricePkg:
            [
              {required: true, message: '整套价格不能为空', trigger: 'blur'}
            ],
          priceVip:
            [
              {required: true, message: '会员单册价格不能为空', trigger: 'blur'}
            ],
          pricePkgVip:
            [
              {required: true, message: '会员整套价格不能为空', trigger: 'blur'}
            ],
          coverImg:
            [
              {required: true, message: '封面图不能为空', trigger: 'blur'}
            ],
          bannerImg:
            [
              {required: true, message: '轮播图不能为空', trigger: 'blur'}
            ],
          itemCount:
            [
              {required: true, message: '绘本册数不能为空', trigger: 'blur'}
            ],
          status:
            [
              {required: true, message: '上下架状态(1上架,0下架)不能为空', trigger: 'blur'}
            ],
          summary:
            [
              {required: true, message: '简介不能为空', trigger: 'blur'}
            ],
          remark:
            [
              {required: true, message: '备注不能为空', trigger: 'blur'}
            ]
        }
      }
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.showCoverImgErrorTip = false
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          this.coverImgErrorTip = ''
          this.dataForm.bannerImg = ''
          this.dataForm.coverImg = ''
          this.dataForm.screenImg = ''
          this.dataForm.summary = ''
          this.dataForm.status = 1
          this.dataForm.contentTypeName = ''
          this.dataForm.price = ''
          this.dataForm.pricePkg = ''
          this.dataForm.priceVip = ''
          this.dataForm.pricePkgVip = ''
          this.dataForm.freeAmount = ''
          this.dataForm.payRight = 'all',
            this.getContentTypeList()
            this.getSource()
        })
      },
      // 获取来源
      getSource () {
        this.$http({
              url: this.$http.adornUrl(`/picbook/combobox/listSource`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.sourceOptions = data.data
              }
            })
      },
      //绘本分类下拉框查询
      getContentTypeList () {
        this.$http({
          // url: this.$http.adornUrl(`/picbook/bookcategory/comboBox`),
          url: this.$http.adornUrl(`/picbook/combobox/listCategory`),
          method: 'post',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.contentTypeOptions = data.data
          }
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/picbook/picbook/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm = data.data.pbBook
                // this.dataForm.contentType = [3]
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        var _this = this
        _this.coverImgErrorTip = ''
        _this.bannerImgErrorTip = ''
        _this.screenImgErrorTip = ''
        _this.$refs['dataForm'].validate((valid) => {
          _this.dataForm.price = _this.$refs.price.value
          _this.dataForm.pricePkg = _this.$refs.pricePkg.value
          _this.dataForm.priceVip = _this.$refs.priceVip.value
          _this.dataForm.pricePkgVip = _this.$refs.pricePkgVip.value
          if (!_this.dataForm.coverImg) {
            _this.coverImgErrorTip = '请上传封面图'
            return
          }
          if (!_this.dataForm.bannerImg) {
            _this.bannerImgErrorTip = '请上传轮播图'
            return
          }
          if (!_this.dataForm.screenImg) {
            _this.screenImgErrorTip = '请上传背景图'
            return
          }
          if (valid) {
            _this.dataForm.price = _this.$refs.price.value || 0
            _this.dataForm.pricePkg = _this.$refs.pricePkg.value || 0
            _this.dataForm.priceVip = _this.$refs.priceVip.value || 0
            _this.dataForm.pricePkgVip = _this.$refs.pricePkgVip.value || 0
            _this.$http({
              url: _this.$http.adornUrl(`/picbook/picbook/${!_this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: _this.$http.adornData({
                pbBook: _this.dataForm
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                _this.$message({
                  message: '操作成功',
                  type: 'success',
                  // duration: 1500,
                  duration: 500,
                  onClose: () => {
                    _this.visible = false
                    _this.$emit('refreshDataList')
                  }
                })
              } else {
                _this.$message.error(data.msg)
              }
            })
          }
        })
      },
      checkNo (value) {
        // var value = this.dataForm.price
        console.log('value:' + value)
        let reg = /^\d*(\.?\d{0,1})/g
        if (value) {
          setTimeout(() => {
            this.dataForm.price = value.match(reg)[0] || ''
          }, 500)
        }
      },
      oninput (e) {
        // 通过正则过滤小数点后两位
        e.target.value = (e.target.value.match(/^\d*(\.?\d{0,2})/g)[0]) || null
      },
      handleCoverImgSuccess (res, file) {
        // this.dataForm.coverImg = URL.createObjectURL(file.raw)
        this.dataForm.coverImg = res.url
        let _this = this
        setTimeout(function () {
          _this.$refs.uploadCoverImg.clearFiles()
        }, 1000)
      },
      beforeCoverImgUpload (file) {
        this.coverImgErrorTip = ''
        if (file.type.indexOf('image') < 0) {
          this.coverImgErrorTip = '图片格式不正确'
          return false
        }
      },
      handleCoverImgError (err, file, fileList) {
        this.coverImgErrorTip = '上传失败'
      },
      handleBannerImgSuccess (res, file) {
        // this.dataForm.bannerImg = URL.createObjectURL(file.raw)
        this.dataForm.bannerImg = res.url
        let _this = this
        setTimeout(function () {
          _this.$refs.uploadBannerImg.clearFiles()
        }, 1000)
      },
      beforeBannerImgUpload (file) {
        this.bannerImgErrorTip = ''
        if (file.type.indexOf('image') < 0) {
          this.bannerImgErrorTip = '图片格式不正确'
          return false
        }
      },
      handleBannerImgError (err, file, fileList) {
        this.bannerImgErrorTip = '上传失败'
      },
      handleScreenImgSuccess (res, file) {
        this.dataForm.screenImg = res.url
        let _this = this
        setTimeout(function () {
          _this.$refs.uploadScreenImg.clearFiles()
        }, 1000)
      },
      beforeScreenImgUpload (file) {
        this.screenImgErrorTip = ''
        if (file.type.indexOf('image') < 0) {
          this.screenImgErrorTip = '图片格式不正确'
          return false
        }
      },
      handleScreenImgError (err, file, fileList) {
        this.screenImgErrorTip = '上传失败'
      },
      previewPicBook () {
        let _this = this
        _this.dataForm.contentTypeName = ''
        if (_this.dataForm.contentType && _this.dataForm.contentType.length > 0 && _this.contentTypeOptions && _this.contentTypeOptions.length > 0) {
          var ret = ''
          _this.contentTypeOptions.forEach(function (option) {
            _this.dataForm.contentType.map(function (type) {
              if (option.id == type) {
                if (ret) {
                  ret = ret + '，' + option.name
                } else {
                  ret = option.name
                }
                return
              }
            })
          })
          _this.dataForm.contentTypeName = ret
        }
        _this.$emit('previewPicBook', _this.dataForm)
      }
    }
  }
</script>
<style scoped lang="less">
  .item-wrapper {
    border: 1px solid #ddd;
    padding: 12px;
    border-radius: 4px;
    margin-bottom: 12px;
    width: 100%;
    .price-item-wrapper {
      display: flex;
      flex-direction: row;
      align-items: center;
      .el-form-item__content {
        float: left;
      }
      .price-input {
        width: 120px;
        margin-left: 10px;
        height: 36px;
        line-height: 36px;
        border-radius: 4px;
        -webkit-appearance: none;
        border: 1px solid #dcdfe6;
        color: #606266;
        padding: 0 15px;
      }
    }
    .item-pic-wrapper {
      display: inline-block;
      .pic {
        display: flex;
        flex-direction: row;
        align-items: center;
        margin-right: 20px;
      }
      .avatar-uploader .el-upload {
        border: 1px solid #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }

      .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
      }
      .coverImg-wrapper {
        .coverImg-uploader-icon {
          font-size: 28px;
          color: #8c939d;
          border: 1px solid #d9d9d9;
          border-radius: 6px;
          width: 125px;
          height: 150px;
          line-height: 150px;
          text-align: center;
        }
        .coverImg {
          width: 125px;
          height: 150px;
          display: block;
        }
      }
      .bannerImg-wrapper {
        .bannerImg-uploader-icon {
          font-size: 28px;
          color: #8c939d;
          border: 1px solid #d9d9d9;
          border-radius: 6px;
          width: 266px;
          height: 150px;
          line-height: 150px;
          text-align: center;
        }
        .bannerImg {
          width: 266px;
          height: 150px;
          display: block;
        }
      }
    }
  }

  .el-form-item {
    margin-bottom: 18px;
  }

  .no-bottom-margin.el-form-item {
    margin-bottom: 0px;
  }

  .error-tip {
    color: #f56c6c;
    font-size: 12px;
    line-height: 1;
    padding-top: 4px;
  }

  /** 去除input输入框样式 */
  input[type=number]::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
</style>
